package com.smart.campus.web.controller.wx;

import com.smart.campus.school.wx.cp.config.WxCpConfiguration;
import com.smart.campus.school.wx.cp.config.WxCpTpConfiguration;
import com.smart.campus.school.wx.cp.utils.JsonUtils;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpTpService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpTpPermanentCodeInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@RestController
@RequestMapping("/wx/cp/portal/{agentId}")
public class WxPortalController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable Integer agentId,
                          @RequestParam(name = "msg_signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        this.logger.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
            signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }

        if (wxCpService.checkSignature(signature, timestamp, nonce, echostr)) {
            return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr);
        }

        return "success";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable Integer agentId,
                       @RequestBody String requestBody,
                       @RequestParam("msg_signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) throws WxErrorException {
        this.logger.info("\n接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            signature, timestamp, nonce, requestBody);

        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(),
            timestamp, nonce, signature);
        this.logger.debug("\n消息解密后内容为：\n{} ", JsonUtils.toJson(inMessage));
        if (inMessage.getAllFieldsMap().containsKey("SuiteTicket")) {
            String suiteTicket = inMessage.getAllFieldsMap().get("SuiteTicket").toString();
            WxCpTpService wxCpTpService = WxCpTpConfiguration.getCpTpService("wwd196420da947673b");
            wxCpTpService.getWxCpTpConfigStorage().expireSuiteTicket();
            wxCpTpService.getWxCpTpConfigStorage().updateSuiteTicket(suiteTicket, 7200);
        }

        if (inMessage.getAllFieldsMap().containsKey("AuthCode")) {
            String authCode = inMessage.getAllFieldsMap().get("AuthCode").toString();
            WxCpTpService wxCpTpService = WxCpTpConfiguration.getCpTpService("wwd196420da947673b");
            WxCpTpPermanentCodeInfo wxCpTpPermanentCodeInfo = null;
            try {
                wxCpTpPermanentCodeInfo = wxCpTpService.getPermanentCodeInfo(authCode);

                ;
                String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/school/department/list?access_token=" + wxCpTpPermanentCodeInfo.getAccessToken();
                ;
                String deptList = wxCpTpService.get(deptUrl, null);
//              WxAccessToken corpToken =  wxCpTpService.getCorpToken(wxCpTpPermanentCodeInfo.getAuthCorpInfo().getCorpId(),wxCpTpPermanentCodeInfo.getPermanentCode());
//              String accessToken = corpToken.getAccessToken();
             /*   String url = "https://qyapi.weixin.qq.com/cgi-bin/school/user/create_student?access_token=" + wxCpTpPermanentCodeInfo.getAccessToken();
                String params = "{\"student_userid\": \"lzy\",\"name\": \"陆忠勇\",\"department\": [24]}";

                String result = wxCpTpService.post(url, params);
                int a = 1;*/
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            this.logger.debug("\n授权企业信息：\n{} ", JsonUtils.toJson(wxCpTpPermanentCodeInfo));
        }


        WxCpXmlOutMessage outMessage = this.route(agentId, inMessage);
        if (outMessage == null) {
            return "success";
        }

    /*String out = outMessage.toEncryptedXml(wxCpService.getWxCpConfigStorage());
    this.logger.debug("\n组装回复信息：{}", out);
    return out;*/
        return "success";
    }

    private WxCpXmlOutMessage route(Integer agentId, WxCpXmlMessage message) {
        try {
            return WxCpConfiguration.getRouters().get(agentId).route(message);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }


}
